<script setup>
import {Delete, Edit, Plus} from '@element-plus/icons-vue'

import {ref} from 'vue'
import {
  classesListService,
  studentAddService,
  studentDeleteService,
  studentListService,
  studentUpdateService
} from '@/api/student.js'
import {QuillEditor} from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import {useTokenStore} from '@/stores/token.js';
import {ElMessage, ElMessageBox} from 'element-plus'

const classes = ref([])

const classId = ref('')
const id = ref('')

const students = ref([])

const pageNum = ref(1)//当前页
const total = ref(0)//总条数
const pageSize = ref(5)//每页条数

const onSizeChange = (size) => {
  pageSize.value = size
  studentList()
}
const onCurrentChange = (num) => {
  pageNum.value = num
  studentList()
}

let pageSizes = [5, 10, 15];

const classesList = async () => {
  let result = await classesListService();

  classes.value = result.data;
}

const studentList = async () => {
  let params = {
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    classId: classId.value ? classId.value : null,
    id: id.value ? id.value : null
  }

  let result = await studentListService(params);

  total.value = result.data.total;
  students.value = result.data.items;

  for (let i = 0; i < students.value.length; i++) {
    let student = students.value[i];
    for (let j = 0; j < classes.value.length; j++) {
      if (student.classId == classes.value[j].id) {
        student.className = classes.value[j].name;
      }
    }
  }
}


classesList()
studentList();

const visibleDrawer = ref(false)


const studentModel = ref({
  id: '',
  name: '',
  age: '',
  gender: '',
  content: '',
  coverImg: '',
  address: '',
  phoneNumber: '',
  classId: ''
})

const tokenStore = useTokenStore();

const addStudent = async () => {

  let result = await studentAddService(studentModel.value);
  ElMessage.success(result.msg ? result.msg : '添加成功');

  visibleDrawer.value = false;

  await studentList()
}


const title = ref('')

const showVisibleDrawer = (row) => {
  visibleDrawer.value = true;
  title.value = '编辑学生信息';

  studentModel.value.name = row.name;
  studentModel.value.classId = row.classId;
  studentModel.value.gender = row.gender;
  studentModel.value.age = row.age;
  studentModel.value.address = row.address;
  studentModel.value.coverImg = row.coverImg;
  studentModel.value.content = row.content;
  studentModel.value.phoneNumber = row.phoneNumber;
  studentModel.value.id = row.id;
}

const updateStudent = async () => {

  try {
    console.log(studentModel.value)
    const result = await studentUpdateService(studentModel.value);
    ElMessage.success(result.msg ? result.msg : '修改成功');
  } catch (error) {
    ElMessage.error('修改失败：' + error.message);
  }

  visibleDrawer.value = false;

  await studentList();
}


const deleteStudent = (row) => {

  ElMessageBox.confirm(
      '你确认要删除该学生吗?',
      '温馨提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(async () => {
        let result = await studentDeleteService(row.id);
        ElMessage({
          type: 'success',
          message: '删除成功',
        })
        await studentList()
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '用户取消了删除',
        })
      })
}

const uploadSuccess = (result) => {
  studentModel.value.coverImg = result.data;
  console.log(result.data);
}


const clearData = () => {
  studentModel.value.id = '';
  studentModel.value.name = '';
  studentModel.value.classId = '';
  studentModel.value.gender = '';
  studentModel.value.age = '';
  studentModel.value.address = '';
  studentModel.value.coverImg = '';
  studentModel.value.content = '';
  studentModel.value.phoneNumber = '';
}


</script>
<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>学生管理</span>
        <div class="extra">
          <el-button type="primary" @click="visibleDrawer = true;clearData();title = '添加学生'">添加学生</el-button>
        </div>
      </div>
    </template>
    <!-- 搜索表单 -->
    <el-form inline>
      <el-form-item label="学生班级：">
        <el-select v-model="classId" placeholder="请选择">
          <el-option v-for="c in classes" :key="c.id" :label="c.name" :value="c.id">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="学生ID：">
        <el-input v-model="id" placeholder="请输入学生ID"></el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="studentList()">搜索</el-button>
        <el-button @click="classId = '';id = ''; studentList()">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 学生列表 -->
    <el-table :data="students" style="width: 100%">
      <el-table-column label="学生姓名" prop="name"></el-table-column>
      <el-table-column label="学号" prop="id"></el-table-column>
      <el-table-column label="班级" prop="className"></el-table-column>
      <el-table-column label="年龄" prop="age"></el-table-column>
      <el-table-column label="联系方式" prop="phoneNumber"></el-table-column>
      <el-table-column label="性别" prop="gender"></el-table-column>
      <el-table-column label="操作" width="100">
        <template #default="{ row }">
          <el-button :icon="Edit" circle plain type="primary" @click="showVisibleDrawer(row)"></el-button>
          <el-button :icon="Delete" circle plain type="danger" @click="deleteStudent(row)"></el-button>
        </template>
      </el-table-column>
      <template #empty>
        <el-empty description="没有数据"/>
      </template>
    </el-table>
    <!-- 分页条 -->
    <el-pagination v-model:current-page="pageNum" v-model:page-size="pageSize" :page-sizes="pageSizes"
                   :total="total" background layout="jumper, total, sizes, prev, pager, next"
                   style="margin-top: 20px; justify-content: flex-end"
                   @size-change="onSizeChange" @current-change="onCurrentChange"/>

    <!-- 抽屉 -->
    <el-drawer v-model="visibleDrawer" :title="title" direction="rtl" size="50%">
      <!-- 添加学生表单 -->
      <el-form :model="studentModel" label-width="100px">
        <el-form-item label="学生姓名">
          <el-input v-model="studentModel.name" placeholder="请输入姓名"></el-input>
        </el-form-item>
        <el-form-item label="学生头像">
          <el-upload :auto-upload="true" :headers="{'Authorization':tokenStore.token}" :on-success="uploadSuccess"
                     :show-file-list="false"
                     action="/api/upload"
                     class="avatar-uploader"
                     name="file">
            <img v-if="studentModel.coverImg" style="width: 20%;" :src="studentModel.coverImg" class="avatar"/>
            <img v-if="!studentModel.coverImg" style="width: 20%;" src="@/assets/avatar.jpg"/>
            <el-icon v-else class="avatar-uploader-icon">
              <Plus/>
            </el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="年龄">
          <el-input v-model="studentModel.age" placeholder="请输入年龄"></el-input>
        </el-form-item>
        <el-form-item label="性别">
          <el-select v-model="studentModel.gender" placeholder="请选择性别">
            <el-option label="男" value="男"></el-option>
            <el-option label="女" value="女"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="家庭住址">
          <el-input v-model="studentModel.address" placeholder="请输入家庭住址"></el-input>
        </el-form-item>
        <el-form-item label="手机号码">
          <el-input v-model="studentModel.phoneNumber" placeholder="请输入电话号码"></el-input>
        </el-form-item>
        <el-form-item label="班级">
          <el-select v-model="studentModel.classId" placeholder="请选择">
            <el-option v-for="c in classes" :key="c.id" :label="c.name" :value="c.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="学生资料">
          <div class="editor">
            <quill-editor v-model:content="studentModel.content" contentType="html" theme="snow">
            </quill-editor>
          </div>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" v-if="title =='添加学生'" @click="addStudent()">添加</el-button>
          <el-button type="primary" v-if="title == '编辑学生信息'" @click="updateStudent()">修改</el-button>
          <el-button type="info" @click="visibleDrawer = false; clearData()">取消</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>

  </el-card>
</template>
<style lang="scss" scoped>
.page-container {
  min-height: 100%;
  box-sizing: border-box;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}

.avatar-uploader {
  :deep(.avatar) {
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }

    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }

    .el-upload:hover {
      border-color: var(--el-color-primary);
    }

    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      text-align: center;
    }
  }
}

.editor {
  width: 100%;

  :deep(.ql-editor) {
    min-height: 200px;
  }
}
</style>